package com.cictec.middleware.tde.rm;

import java.io.IOException;
import java.net.InetSocketAddress;

import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.transport.socket.SocketSessionConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.cictec.middleware.commons.spring.SpringContextHolder;
import com.cictec.middleware.commons.utils.PropertiesUtils;
import com.cictec.middleware.tde.PlatformProtocolServer;

@Component
public class RmPlatformProtocolServer implements PlatformProtocolServer {

	public static Logger logger = LoggerFactory.getLogger(RmPlatformProtocolServer.class);

	private static String middlewareHost = "0.0.0.0"; // 默认本机
	private static int vehicleDeviceAcceptorPort = 9650; // 中间件服务端口

	@Override
	public void start() {
		try {
			startMina();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 关闭锐明协议解析服务mina服务端
	 */
	@Override
	public void shutdown() {

		IoAcceptor rmIoAcceptor = SpringContextHolder.getBean("rmIoAcceptor");
		rmIoAcceptor.unbind();
		rmIoAcceptor.dispose(false);
	}

	/**
	 * a5主机 mina服务器启动
	 * 
	 * @throws IOException
	 */
	private static void startMina() throws IOException {

		/* ***********************************************************************/
		/* **************** 中间件服务 start **************************************/
		/* ***********************************************************************/
		middlewareHost = PropertiesUtils.getString("vehicle.device.host", "0.0.0.0");
		vehicleDeviceAcceptorPort = PropertiesUtils.getIntValue("vehicle.device.port", 9650);

		// 车载设备的监听服务
		IoAcceptor vehicleDeviceAcceptor = SpringContextHolder.getBean("rmIoAcceptor");
		SocketSessionConfig sessionConfig = (SocketSessionConfig) vehicleDeviceAcceptor.getSessionConfig();
		sessionConfig.setTcpNoDelay(true);

		// 读写通道10秒内无操作进入空闲状态
		sessionConfig.setIdleTime(IdleStatus.BOTH_IDLE, 2 * 60);
		// 绑定逻辑处理器
		vehicleDeviceAcceptor.bind(new InetSocketAddress(middlewareHost, vehicleDeviceAcceptorPort));
		logger.info("【车载设备服务端】【锐明协议】启动成功...   ip:{} 端口号为：{}", middlewareHost, vehicleDeviceAcceptorPort);

		/* *****************************************************************/
		/* **************** 中间件服务 end **********************************/
		/* *****************************************************************/
	}

}
